//
//  HTTPClient.swift
//  Edaixi-iOS
//
//  Created by 刘树华 on 2017/11/28.
//  Copyright © 2017年 刘树华. All rights reserved.
//

enum HTTPCustomError : Error {
    case serverError(Int) , nullData ,serializationDataNull
}



import Foundation
import Alamofire

class HTTPClient:SessionManager  {
    
    static let Shared = { () -> HTTPClient in
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 15
        let manager =  HTTPClient.init(configuration: config)
    
        return manager
    }()
    func httpRequest (method:HTTPMethod,url:URLConvertible,parameters:Parameters?,success: @escaping (Any?)->(),failed:@escaping (Error?)->()) -> DataRequest {
        return HTTPClient.Shared.request(url, method: method, parameters: parameters).validate({ (request, response, data) -> Request.ValidationResult in
            
            if response.statusCode != 200 {
                return .failure(HTTPCustomError.serverError(response.statusCode))
            }else{
                guard data != nil else {return .failure(HTTPCustomError.nullData) }
                return .success
            }
        }).responseJSON(completionHandler: { (data) in
            
            if data.error != nil{
                failed(data.error)
            }else{
                if data.value != nil {
                    success(data.value)
                }else{
                    failed(HTTPCustomError.serializationDataNull)
                }
            }
        })
    }
    
    
    
}
